package com.ruoyi.apiserver.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.aiworkflow.services.ICozeWorkflow;
import com.ruoyi.apiserver.base.MhBaseController;
import com.ruoyi.apiserver.domain.RandomQuestionsDTO;
import com.ruoyi.apiserver.domain.TestResultMoreVO;
import com.ruoyi.apiserver.config.AESConfig;
import com.ruoyi.apiserver.services.ICozeServices;
import com.ruoyi.apiserver.services.ReportGenerationProducerService;
import com.ruoyi.apiserver.utils.AESUtils;
import com.ruoyi.apiserver.utils.JwtUtils;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.AesCbcEncrypt;
import com.ruoyi.common.utils.AsymmetricEncryption;
import com.ruoyi.mhorders.domain.MhOrder;
import com.ruoyi.mhorders.service.IMhOrderService;
import com.ruoyi.test.domain.MhTest;
import com.ruoyi.test.domain.MhTestMore;
import com.ruoyi.test.domain.MhTestQuestion;
import com.ruoyi.test.service.IMhTestMoreService;
import com.ruoyi.test.service.IMhTestQuestionService;
import com.ruoyi.test.service.IMhTestService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.PageUtils.startPage;

@RestController
@Api(tags = "测试模块接口")
@RequestMapping("/api/tests")
public class TestsController extends MhBaseController {

    @Autowired
    private IMhTestService mhTestService;

    @Autowired
    private IMhOrderService mhOrderService;

    @Autowired
    private ICozeWorkflow cozeWorkflowService;

    @Autowired
    private IMhTestQuestionService mhTestQuestionService;


    @Autowired
    private IMhTestMoreService mhTestMoreService;

    @Autowired
    private ICozeServices cozeServices;


    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private AESConfig aesConfig;


    @Autowired
    private ReportGenerationProducerService reportGenerationProducerService;

    @GetMapping("/list")
    public TableDataInfo list(MhTest mhTest) {

        mhTest.setUserId(getUserId());
        startPage();
        List<MhTest> list = mhTestService.selectMhTestList(mhTest);
        TableDataInfo rspData = new TableDataInfo();

        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("获取成功！");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }


    @PostMapping("/create")
    public AjaxResult create(@RequestBody MhTest mhTest) throws JsonProcessingException {

        if (mhTest.getTestValue().equals("")) {
            return AjaxResult.error("参数有误：测试结果值获取为空");
        }
//        mhTest.setTestType("mbti:");
        mhTest.setTestHasmoreinfo(0L);
        mhTest.setUserId(getUserId());
        mhTest.setCreateTime(new Date());
        mhTest.setTestTime(new Date());

        //获取test_id
        int count = mhTestService.insertMhTest(mhTest);


        String queryJson = "我的测试结果是" + mhTest.getTestResult() + "，测试原始值：" + mhTest.getTestValue() + ",现在只要基础画像的内容";
        Map<String, Object> json = cozeServices.getJSON(queryJson);

        for (Map.Entry<String, Object> entry : json.entrySet()) {

            ObjectMapper mapper = new ObjectMapper();
            String JsonStr = mapper.writeValueAsString(entry.getValue());
//            mhTest.setTestValue(JsonStr);

            MhTestMore mhTestMore = new MhTestMore();
            mhTestMore.setKey(entry.getKey());
            mhTestMore.setOrderNo("");
            mhTestMore.setSort(1L);
            mhTestMore.setIsEncrypted(0L);
            mhTestMore.setCreateTime(new Date());
            mhTestMore.setUserId(getUserId());
            mhTestMore.setJsonValue(JsonStr);
            mhTestMore.setTestId(mhTest.getId());

            mhTestMoreService.insertMhTestMore(mhTestMore);
        }

        if (count > 0) {
            return AjaxResult.success("创建成功！", mhTest);
        } else {
            return AjaxResult.error("创建失败！");
        }

    }


    @PostMapping("/getTestResult")
    public AjaxResult getTestResult(@RequestBody MhTest mhTest) throws JsonProcessingException {

        if (mhTest.getId() <= 0) {
            return AjaxResult.error("参数有误：test-id为空");
        }
        MhTest model = mhTestService.selectMhTestById(mhTest.getId());

        MhTestMore mhTestMore = new MhTestMore();
        mhTestMore.setKey("基础画像");
        mhTestMore.setTestId(model.getId());
        List<MhTestMore> mhTestMores = mhTestMoreService.selectMhTestMoreList(mhTestMore);

        if (mhTestMores.size() <= 0) {
            return AjaxResult.error("获取失败！当前报告为空！");
        }

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(mhTestMores.get(0));
        model.setBaseData(jsonString);
        if (model != null) {
            return AjaxResult.success("获取成功！", model);
        } else {
            return AjaxResult.error("获取失败！");
        }

    }

    @GetMapping("/getTestResultInfo")
    public AjaxResult getTestResultMore(@RequestParam Long orderId, @RequestParam Long TestId) throws JsonProcessingException {


        TestResultMoreVO vo = new TestResultMoreVO();

        MhTest mhTest = new MhTest();
        if (orderId > 0) {
            //return AjaxResult.error("参数有误：orderId为空");
            //获取订单信息
            MhOrder mhOrder = mhOrderService.selectMhOrderById(orderId);
            if (mhOrder == null) {
                return AjaxResult.error("数据有误：mhOrder为空");
            }
            //查询Test信息
            mhTest = mhTestService.selectMhTestById(mhOrder.getProductId());
        }
        if (TestId > 0) {
            //查询Test信息
            mhTest = mhTestService.selectMhTestById(TestId);
        }
        if (mhTest == null) {
            return AjaxResult.error("数据有误：mhTest为空");
        }

        boolean HasOnlyFree = false;
        if (mhTest.getTestHasmoreinfo() != null && mhTest.getTestHasmoreinfo() > 0) {
            HasOnlyFree = true;
        }
        //获取报表信息
        MhTestMore mhTestMore = new MhTestMore();
//        mhTestMore.setTestId(mhTest.getId());
        mhTestMore.setTestId(mhTest.getId());

        List<MhTestMore> mhTestMores = mhTestMoreService.selectMhTestMoreList(mhTestMore);

        //进行加密
        Map<String, Object> map = new HashMap<>();
        for (MhTestMore m : mhTestMores) {
            if (m.getKey().equals("基础画像")) {
                ObjectMapper objectMapper = new ObjectMapper();
                Map ItemMap1 = objectMapper.readValue(m.getJsonValue(), map.getClass());
                vo.setBaseData(ItemMap1);
            }
            if (HasOnlyFree) {
                if (m.getKey().equals("基础画像")) {
                    continue;
                }
                if (map.containsKey(m.getKey())) {
                    continue;
                }
                ObjectMapper objectMapper = new ObjectMapper();
                Map ItemMap = objectMapper.convertValue(m, map.getClass());
                map.put(m.getKey(), ItemMap);
            }

        }
        if (map.size() > 0) {
            ObjectMapper objectMapper = new ObjectMapper();
            String MapStr = objectMapper.writeValueAsString(map);
            // 添加AES加密
            try {
                // 从配置中获取AES密钥
//                String aesKey = aesConfig.getKey();
//                String encryptedData = AESUtils.encrypt(MapStr, aesKey);
                String key = aesConfig.getKey();
                String json = MapStr;
                AesCbcEncrypt aesCbcEncrypt = new AesCbcEncrypt(key, aesConfig.getIv());
                String encryptedData = aesCbcEncrypt.encrypt(json);
                System.out.println("a=>" + encryptedData);
                vo.setEncryptDataStr(encryptedData);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error("加密失败：" + e.getMessage());
            }
        }

        vo.setTestType(mhTest.getTestType());
        vo.setPaid(mhTest.getTestHasmoreinfo() == 1);
        return AjaxResult.success("获取报告成功", vo);
    }


    @PostMapping("/getTestResultMore")
    public AjaxResult getTestResultMore(@RequestBody MhTest mhTest) throws JsonProcessingException {
        TestResultMoreVO vo = new TestResultMoreVO();

        if (mhTest.getId() <= 0) {
            return AjaxResult.error("参数有误：test-id为空");
        }

        if (mhTest.getOrderNO().equals("")) {
            return AjaxResult.error("参数有误：order-no为空");
        }

        MhTestMore mhTestMore = new MhTestMore();
        mhTestMore.setTestId(mhTest.getId());
        mhTestMore.setOrderNo(mhTest.getOrderNO());
        mhTestMore.setUserId(getUserId());

        List<MhTestMore> mhTestMores = mhTestMoreService.selectMhTestMoreList(mhTestMore);

        //进行加密
        Map<String, Object> map = new HashMap<>();
        for (MhTestMore m : mhTestMores) {
            if (m.getKey().equals("基础画像")) {
                continue;
            }
            if (map.containsKey(m.getKey())) {
                continue;
            }
            ObjectMapper objectMapper = new ObjectMapper();
            Map ItemMap = objectMapper.convertValue(m, map.getClass());
            map.put(m.getKey(), ItemMap);
        }
//        vo.setEncryptData(map);
        ObjectMapper objectMapper = new ObjectMapper();
        String MapStr = objectMapper.writeValueAsString(map);
//        vo.setEncryptDataStr(MapStr);

        // 添加AES加密
        try {
            // 从配置中获取AES密钥
            String aesKey = aesConfig.getKey();
            String encryptedData = AESUtils.encrypt(MapStr, aesKey);
            vo.setEncryptDataStr(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("加密失败：" + e.getMessage());
        }

        //获取数据
        return AjaxResult.success("获取成功！", vo);
    }


    @Anonymous
    @PostMapping("/RandomQuestions")
    public AjaxResult RandomQuestions(@RequestBody RandomQuestionsDTO dto) {
        int[] queryCount = new int[]{20, 48, 96, 169, 200};
        
        // 验证题目数是否有效
        boolean isValidCount = false;
        for (int count : queryCount) {
            if (count == dto.getCount()) {
                isValidCount = true;
                break;
            }
        }
        
        if (!isValidCount) {
            return AjaxResult.error("参数有误：题目数必须是20、48、96、169或200中的一个");
        }
        
        List<MhTestQuestion> mhTestQuestions = mhTestQuestionService.selectRandomQuestionsByDimension(dto.getCount());
        return AjaxResult.success("获取题库成功！", mhTestQuestions);
    }


//    @Anonymous
//    @GetMapping("/testinfo")
//    public Object Test() throws JsonProcessingException {
//        return mhTestQuestionService.selectRandomQuestionsByDimension(20);
//    }


}
